import QtQuick 1.0
import com.nokia.symbian 1.1
import "../delegates"
import "../js/core.js" as Core

Page {
    id: root

    TitleHeader {
        id: header;
        text: "Quiz - Select a Topic"
    }

    ListModel {
        id: quizModel
    }

    ListView {
        id:  quizView
        anchors {
            left: root.left; right: root.right;
            top: header.bottom; bottom: parent.bottom;
        }
        model: quizModel
        delegate: ItemDelegate {
            id: itemDelegate
            name: model.quizTopicName
            onClicked: {
                root.pageStack.push(window.quizItemPage, {quizTopicName: model.quizTopicName, quizTopicID: model.quizTopicID});
            }
            onCheckBoxClicked: {
                if(checked != model.checked) {
                    quizModel.setProperty(index, 'checked', checked);
                    Core.updateQuizTopicChecked(model);
                }
            }
        }
        clip: true
    }

    TextInputDialog{
        id: quizTopicCreateDialog
        dialogTitleText: "Add Topic"
        placeHolderText:"Enter Topic Name.."

        onAccepted: {
            if(userInput !== "") {
                Core.addQuizTopic(userInput);
                updateUi();
            }
        }
    }

    TextInputDialog{
        id: quizTopicEditDialog
        dialogTitleText: "Edit Topic"
        placeHolderText:"Enter Topic Name.."

        onAccepted: {
            if(userInput !== "") {
                Core.updateQuizTopicName(userInput);
                updateUi();
            }
        }
    }

    ConfirmDialog{
        id:deleteDialog
        dialogTitleText: "Delete Confirmation"
        messageText: "      Are you sure you want\n to delete the selected quizes?"

        onAccepted: {
            Core.deleteQuizTopics();
            updateUi();
        }
    }

    tools: ToolBarLayout {
        ToolButton{
            iconSource: "toolbar-back"
            onClicked:
                root.pageStack.pop();
        }
        ToolButton{
            iconSource: "toolbar-add"
            onClicked:
                quizTopicCreateDialog.open();
        }
        ToolButton{
            iconSource: "editIcon.png"
            onClicked:
                quizTopicEditDialog.open();
        }
        ToolButton{
            iconSource: "toolbar-delete"
            onClicked:{
                deleteDialog.open();
            }
        }
    }

    onStatusChanged: {
        if(status == PageStatus.Activating) {
            updateUi();
        }
    }

    function updateUi()
    {
        quizView.model = 0;
        Core.readQuizTopics(quizModel);
        quizView.model = quizModel;
    }

    Component.onCompleted: {
        Core.openDB();
    }

}
